<?php
class cls_data_product
{
	var $table_name = '`product`' ;
	var $table_name2 = '`productstatistic`' ;
	var $db_name = 'b2c';

	function countRec($fname,$where) {
		$sql = "SELECT $fname FROM {$this->table_name} a left join productstatistic ps on a.ID = ps.ProductID $where";
		$result = $this->db->getAll($sql);
		return count($result);
	}

	function get_product_list($page,$rp,$where,$sort)
	{


		if (!$page) $page = 10;
		if (!$rp) $rp = 10;

		$start = (($page-1) * $rp);

		$limit = "LIMIT $start, $rp";
		
		$sql = "select a.id,a.Name,a.Publisher ,ps.Quantity,a.Price ,b.name as Category ,a.ISBN from {$this->table_name} as a join categorytype as b on a.Category  = b.id  left join productstatistic ps on a.ID = ps.ProductID $where $sort $limit";
		$product_list = $this->db->getAll($sql);

		return $product_list;
	}
	
	
	function modify_quantity($items)
	{
		$item = explode(',', $items,2);
		$sql = "update {$this->table_name2} set quantity=quantity+{$item[1]} where productid={$item[0]}";
		
		$this->db->query($sql);
	}

	function reduce_quantity($product_id, $num)
	{
		$sql = "update {$this->table_name2} set quantity=quantity-{$num} where productid={$product_id}";
	
		$this->db->query($sql);
	}
	
	function add_product($name,$isbn,$description,$author,$prolang,$quantity,$price,$category,$path,$totalpage,$publisher)
	{
		$sql_p = "Insert into {$this->table_name} values('','{$name}','{$description}','{$path}','{$totalpage}','{$publisher}','{$prolang}','{$author}','{$price}','{$category}','{$isbn}')";
		$this->db->query($sql_p);
		
		$sql_get_id = "select max(ID) as ID from  {$this->table_name}";
		$result = $this->db->getAll($sql_get_id);
		$pid = $result[0]['ID'];
	    p($pid);
		$sql_ps = "Insert into {$this->table_name2} values('{$pid}','{$quantity}',0)";
	    $this->db->query($sql_ps);
		
		
	}
	
	function  delete_product($items)
	{
		$sql = "DELETE FROM {$this->table_name} WHERE `id` IN ($items)";
		$this->db->query($sql);
		
	}
	
}